class Backend::SessionsController < Backend::BaseController

  skip_before_action :logged_in?
  skip_before_action :store_referer, only: [:new, :create]
  layout 'backend_login'
  #初始化登录页面
  def new
    @admin = AdminUser.new
  end

  # 登录动作
  def create
    @admin = AdminUser.new(session_params.permit!)
    if !verify_rucaptcha?
      flash[:alert] = '验证码错误'
      render action: :new and return
    end
    admin = AdminUser.find_by(login: session_params[:login])
    unless admin.present?
      flash[:alert] = '该帐号不存在'
      render(action: :new) && return
    end
    @admin = admin
    if admin.status == 0
      flash[:alert] = '该帐号已被停用'
      render(action: :new) && return
    end
    if admin.authenticate(session_params[:password])
      set_current_admin(admin)
      redirect_to backend_root_path
    else
      flash[:alert] = '用户密码错误'
      render(action: :new) && return
    end
  end

  def destroy
    reset_session
    redirect_to backend_login_path
  end


  private

  def session_params
    params.require(:admin_user).permit!
  end

  def set_current_admin(admin)
    session[:current_admin_id] = admin.id
    # 因为后台现在只有一个登录入口，所以在这个方法里记登录日志
    # log = admin.administrator_logs.new(kind: 1, ip: request.remote_ip)
    #   log = AdministratorLog.new(administrator: admin, kind: 1, ip: request.remote_ip)
    #   log.save
  end


end
